package MyThread;

/**
 * volatile 两个线程依次打印 奇数和偶数
 */

class Lock {
    int value = 0;

    public void increment() {
        synchronized (this) {
            value++;
        }
    }

    public int get() {
        synchronized (this) {
            return value;
        }
    }
}

public class Thread_synchronize1 {
    private static volatile boolean flag4Volatile = true;
    private static int index = 1;
    private static int end = 60;
    private static volatile int flag3 = 0;
    private static Lock lock = new Lock();

    /**
     * volatile 三个线程依次打印 5 个数
     */
    public static void testVolatile3_5() throws InterruptedException {
        Thread t0 = new Thread(() -> {
            while (index <= end) {
                synchronized (lock) {
                    if (lock.get() % 3 == 0) {

                        System.out.print(Thread.currentThread().getName() + ":");
                        for (int i = 0; i <= 4; i++) {
                            System.out.print(" " + index++);
                        }
                        System.out.println();
                        lock.increment();
                    }
                }
            }
        });
        Thread t1 = new Thread(() -> {
            while (index <= end) {
                synchronized (lock) {
                    if (lock.get() % 3 == 1) {

                        System.out.print(Thread.currentThread().getName() + ":");
                        for (int i = 0; i <= 4; i++) {
                            System.out.print(" " + index++);
                        }
                        System.out.println();
                        lock.increment();
                    }
                }
            }
        });
        Thread t2 = new Thread(() -> {
            while (index <= end) {
                synchronized (lock) {
                    if (lock.get() % 3 == 2) {

                        System.out.print(Thread.currentThread().getName() + ":");
                        for (int i = 0; i <= 4; i++) {
                            System.out.print(" " + index++);
                        }
                        System.out.println();
                        lock.increment();
                    }
                }
            }
        });
        t0.start();
        t1.start();
        t2.start();

    }

    public static void main(String[] args) throws Exception {
        testVolatile3_5();
    }
}
